package ca.concordia.comp6231.udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

import ca.concordia.comp6231.server.StationServer;

public class UDPService implements Runnable{
	private final int portNo;
	private final StationServer rmiServer;
	public UDPService(int portNo, StationServer rmiServer) {
		this.portNo = portNo;
		this.rmiServer = rmiServer;
	}

	@Override
	public void run() {
		DatagramSocket aSocket = null;
		try {
			aSocket = new DatagramSocket(portNo);
			byte[] buffer = new byte[1000];
			
			while (true) {
				DatagramPacket request = new DatagramPacket(buffer, buffer.length);
				aSocket.receive(request);
				
				String requestString = new String(request.getData());
				String response = processRequest(requestString);
				
				DatagramPacket reply = new DatagramPacket(
															response.getBytes(),
															response.length(), 
															request.getAddress(),
															request.getPort()
														 );
				aSocket.send(reply);
			}
		} catch (SocketException e) {
			System.out.println("Socket: " + e.getMessage());
		} catch (IOException e) {
			System.out.println("IO: " + e.getMessage());
		} finally {
			if (aSocket != null)
				aSocket.close();
		}		
	}
	
	private String processRequest(String requestString){
		String response = "";
		System.out.println("requestString : " + requestString);
		
		String testString = "getRecordCount";
		if(testString.equalsIgnoreCase(requestString.trim())){
			response = rmiServer.getServerName() + " " + rmiServer.getRecordCountForCurrentServer(); 
		}else{
			response = "Unknown request";
		}
		
		return response;
	}
}
